package org.xxpay.pay.channel.yunsfpay.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xxpay.core.common.util.MD5Util;

import java.util.*;

/**
 * payUtils渠道工具类
 * @author hjj
 * @email  1977947499@qq.com
 *
 */
public class PayUtils {

	private static final Logger logger = LoggerFactory.getLogger(PayUtils.class);

	/**
	 * 字符串格式：{"ret_code": "0","ret_msg": "交易成功"} 转为Map
	 *
	 * @param jsonStr json字符串
	 *
	 * @return Map<String,Object>
	 */
	public static Map<String, Object> parseJSON2Map(String jsonStr) {
		if(jsonStr==null){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject json = JSON.parseObject(jsonStr); // 字符串转json对象
		// 遍历
		for (Object k : json.keySet()) {
			Object v = json.get(k);
			if (!"".equals(v) && null != v) {
				map.put(k.toString(), v.toString());
			}
		}
		return map;
	}

	/**
	 * Map转为json字符串
	 *
	 * @return jsonStr json字符串
	 */
	public static String parseMap2JSONStr(Map<String, Object> map) {
		JSONObject jsonstr = JSONObject.parseObject(JSON.toJSONString(map));
		return jsonstr.toString();
	}

	/**
	 * 字典排序后，结果转大写
	 * @param paramMap
	 * @param merKey
	 * @return
	 */
	public static String getSign(Map<String, Object> paramMap, String merKey) {
		SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap);
		StringBuffer stringBuffer = new StringBuffer();
		for (Map.Entry<String, Object> m : smap.entrySet()) {
			Object value = m.getValue();
			if (value != null && !"".equals(value.toString().trim())) {
				stringBuffer.append(m.getKey()).append("=").append(m.getValue()).append("&");
			}
		}
		stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());

		String argPreSign = stringBuffer.append("&key=").append(merKey).toString();
		logger.info("签名源串："+argPreSign);
		String signStr = MD5Util.string2MD5(argPreSign).toUpperCase();
		logger.info("签名结果："+signStr);
		return signStr;
	}

	/**
	 * 字典排序后，结果转大写===>>>云闪付
	 * @param paramMap
	 * @return
	 */
	public static String getYunsfSign(Map<String, Object> paramMap) {
		logger.info("=========>>>start");
		SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap);
		StringBuffer stringBuffer = new StringBuffer();
//		for (Map.Entry<String, Object> m : smap.entrySet()) {
//			Object value = m.getValue();
//			if (value != null && !"".equals(value.toString().trim())) {
//				stringBuffer.append(m.getKey()).append("=").append(m.getValue()).append("&");
//			}
//		}
//		stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
		stringBuffer.append(paramMap.get("dt"));
		stringBuffer.append(paramMap.get("mark"));
		stringBuffer.append(paramMap.get("money"));
		stringBuffer.append(paramMap.get("no"));
		stringBuffer.append(paramMap.get("type"));
		stringBuffer.append(paramMap.get("signkey"));
		stringBuffer.append(paramMap.get("userids"));
		stringBuffer.append(paramMap.get("version"));
		logger.info("=========>>>end,{}",stringBuffer.toString());

		String argPreSign = stringBuffer.toString();
		logger.info("签名源串："+argPreSign);
		String signStr = MD5Util.string2MD5(argPreSign);
		logger.info("签名结果："+signStr);
		return signStr;
	}

	public static String sendPost(String url, Map<String, Object> resMap) throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpPost postMethod = new HttpPost(url);

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
		postMethod.setConfig(requestConfig);
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		for (String key : resMap.keySet()) {
			if(resMap.get(key) != null){
				nvps.add(new BasicNameValuePair(key, resMap.get(key).toString()));
			}

		}
		postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

		HttpResponse resp = httpClient.execute(postMethod);
		String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
		return respString;
	}

	/**
	 * 异步通知验签
	 * */
	public static boolean verifySignature(Map<String,Object> map, String merKey) throws Exception{
		String sign = map.get("sign").toString();
		map.remove("sign");
		String sign_ = getSign(map, merKey);
		return sign.equals(sign_);
	}

	public static String getHtmlContent(String url){
		StringBuffer content = new StringBuffer();
		content.append("<html><head></head><body><form id=\"pay_form\" name=\"pay_form\" action=\""+url+"\" method=\"POST\">");
		content.append("</form>");
		content.append("<script language=\"javascript\">window.onload=function(){window.location= \""+url+"\";}</script></body></html>");

		return content.toString();
	}

	public static String getHtmlContent(String url,Map<String, Object> h5PayMap){
		StringBuffer content = new StringBuffer();
		content.append("<html><head></head><body><form id=\"pay_form\" name=\"pay_form\" action=\""+url+"\" method=\"POST\">");
		for(String key:h5PayMap.keySet()){
			String value = h5PayMap.get(key).toString();
			if(!"".equals(value) && null != value){
				content.append("<input type=\"hidden\" ");
				content.append("name=\"").append(key).append("\" ");
				content.append("value=\"").append(h5PayMap.get(key).toString()).append("\" ");
				content.append("/>");
			}
		}
		content.append("</form>");
		content.append("<script language=\"javascript\">window.onload=function(){document.pay_form.submit();}</script></body></html>");

		return content.toString();
	}
}
